import 'package:dio/dio.dart';
import 'package:flutter_van_android/utils/log_util.dart';

import 'mmkv_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_van_android/utils/router_manager.dart';
import 'package:flutter_van_android/pages/login_page.dart';

class DioInterceptors extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 如果用户已登录且 Token 不为空，则添加 Authorization Header
    var token = MmkvUtil.getString("token");
    if (token != null && token.isNotEmpty) {
      options.headers['token'] = token;
    }

    LogUtil.d('发送请求: ${options.uri}');
    LogUtil.d('发送请求: ${options.headers}');
    handler.next(options); // 继续请求
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // 处理响应
    LogUtil.d('响应数据: ${response.data}');
    handler.next(response); // 继续响应
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    // 统一错误处理
    LogUtil.e('发生错误: ${err.message}');
    if (err.response?.statusCode == 401) {
      MmkvUtil.saveString("token", "");
      Navigator.pushNamedAndRemoveUntil(
        navigatorKey.currentContext!,
        RouterHelper.typeName(LoginPage),
        (route) => false,
      );
    }
    handler.next(err); // 继续错误
  }
}
